# Copyright (C) 2005-2006 Frederic Back <fredericback@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

import os
import gtk
import gobject
import pickle

class HistoryView( gtk.ScrolledWindow ):
    ''' Manage a list of sql commands in a TreeView '''

    __gsignals__ = {
        'activated' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)),
        'command-added' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,))
    }

    def __init__(self):
        gtk.ScrolledWindow.__init__(self)

        self.count = 0
        self.maxHistorySize = 500

        self.ls = gtk.ListStore(str)
        self.tree = tv = gtk.TreeView(self.ls)
        self.tree.set_headers_visible(False)
        tv.connect("row-activated",self.cb_rowActivated)
        tr = gtk.CellRendererText()
        tv.append_column(gtk.TreeViewColumn("SQL Commands", tr, text=0) )
        self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        self.add(tv)
        self.show_all()
        
    def saveHistory(self, filename):
        try: f = open(filename,"w")
        except Exception, e:
            print e
            return
        lst = []        
        it = self.ls.get_iter_first()
        while it is not None:
            lst.append(self.ls.get_value(it,0))
            it = self.ls.iter_next(it)
        pickle.dump(lst,f)
        f.close()
    
    def loadHistory(self, filename):
        try: f = open(filename,"r")
        except Exception, e: return
        try:
            lst = pickle.load(f)
            #print lst
            for e in lst:
                self.ls.append( [e] )
        except Exception, e:
            print "Could not parse history from %s"%filename
            print e
        f.close()

    def cb_rowActivated(self, treeview, path, view_column):
        command = self.ls.get_value( self.ls.get_iter(path), 0 )
        self.emit('activated', command)
    
    def addCommand(self, command):

        if command.count(";") > 3:
            print "Command not added to history: More than three semicolons found"
            return

        if len(command) > 255:
            print "Command not added to history: Longer than 255 chars"
            return

        # ignore if identical with last command
        it = self.ls.get_iter_first()
        if it != None:
            v = self.ls.get_value(it,0) 
            if v == command: return

        self.ls.prepend( [command] )
        self.tree.set_cursor(0)
        self.count += 1

        if self.count > self.maxHistorySize:
            self.ls.remove( self.ls.get_iter(self.count) )
            self.count -= 1

        self.emit('command-added', command)

gobject.type_register(HistoryView)
